package com.oim.fx.view.pane;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;

import com.oim.core.bean.Department;
import com.oim.core.business.box.PersonalBox;
import com.oim.core.business.box.UserDataBox;
import com.oim.core.business.controller.ChatController;
import com.oim.core.business.controller.RemoteController;
import com.oim.core.business.manage.DepartmentChatManage;
import com.oim.core.business.manage.DepartmentManage;
import com.oim.core.business.manager.ChatManage;
import com.oim.core.business.manager.HeadImageManager;
import com.oim.core.business.manager.ImageManager;
import com.oim.core.business.manager.PromptManager;
import com.oim.core.business.manager.SettingManager;
import com.oim.core.business.sender.DepartmentChatSender;
import com.oim.core.common.action.BackAction;
import com.oim.core.common.action.BackInfo;
import com.oim.core.common.component.file.FileHandleInfo;
import com.oim.core.common.util.AppCommonUtil;
import com.oim.fx.common.box.ImageBox;
import com.oim.fx.common.component.IconButton;
import com.oim.fx.common.component.IconPane;
import com.oim.fx.common.util.ContentUtil;
import com.oim.fx.ui.chat.ChatItem;
import com.oim.fx.ui.chat.SimpleHead;
import com.oim.fx.ui.chat.pane.NodeChatPane;
import com.oim.fx.ui.list.ListRootPanel;
import com.oim.fx.view.EnterpriseChatListView;
import com.only.common.util.OnlyDateUtil;
import com.only.fx.common.action.EventAction;
import com.onlyxiahui.app.base.AppContext;
import com.onlyxiahui.im.bean.UserData;
import com.onlyxiahui.im.message.data.chat.Content;
import com.onlyxiahui.im.message.data.chat.Item;
import com.onlyxiahui.oim.face.bean.FaceInfo;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;

public class PaneEnterpriseChatListViewImpl extends PaneChatListViewImpl implements EnterpriseChatListView {

	protected Map<String, ListRootPanel> departmentUserListMap = new ConcurrentHashMap<String, ListRootPanel>();

	public PaneEnterpriseChatListViewImpl(AppContext appContext) {
		super(appContext);
	}

	@Override
	public boolean isDepartmentChatShowing(String departmentId) {
		String key = this.getDepartmentKey(departmentId);
		return chatListFrame.isShowing() && (null != tempChatItem && key.equals(tempChatItem.getAttribute("key")));
	}

	@Override
	public boolean hasDepartmentChat(String departmentId) {
		String key = this.getDepartmentKey(departmentId);
		return hasChatItem(key);
	}

	@Override
	public void show(Department department) {
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				ChatItem chatItem = getDepartmentChatItem(department);
				NodeChatPane chatPanel = getDepartmentChatPanel(department);
				select(chatItem, chatPanel);
				DepartmentChatManage chatManage = appContext.getManager(DepartmentChatManage.class);
				chatManage.showDepartmentCaht(department);
			}
		});
	}

	@Override
	public void departmentChat(Department department, UserData userData, Content content) {
		if (null != userData) {
			PersonalBox pb = appContext.getBox(PersonalBox.class);
			UserData user = pb.getUserData();
			boolean isOwn = user.getId().equals(userData.getId());
			String name = AppCommonUtil.getDefaultShowName(userData);
			String time = OnlyDateUtil.getCurrentDateTime();
			
			
			Platform.runLater(new Runnable() {
				@Override
				public void run() {
					NodeChatPane chatPanel = getDepartmentChatPanel(department);
					HeadImageManager him = appContext.getManager(HeadImageManager.class);
					String headPath = him.getUserHeadImagePath(userData.getId(), 40);
					String orientation = isOwn ? "right" : "left";
					insertShow(chatPanel, name, headPath, time, orientation, content);
				}
			});
		}
	}

	private ChatItem getDepartmentChatItem(Department department) {
		String key = this.getDepartmentKey(department.getId());
		ChatItem item = chatItemMap.get(key);
		if (null == item) {
			item = new ChatItem();
			item.addAttribute("key", key);
			chatItemMap.put(key, item);
			item.addCloseAction(new ChatItemCloseEvent(key));
			item.setOnMouseClicked(new ChatItemClickedEvent(key));
		}
		item.setText(department.getName());
		String headPath = "Resources/Images/Enterprise/Head/2.png";
		Image image = ImageBox.getImagePath(headPath);
		item.setImage(image);
		return item;
	}

	private NodeChatPane getDepartmentChatPanel(Department department) {
		String departmentId = department.getId();
		String key = this.getDepartmentKey(department.getId());
		NodeChatPane item = chatPanelMap.get(key);
		if (null == item) {
			item = new NodeChatPane();
			item.addAttribute("key", key);
			item.addAttribute("departmentId", department.getId());
			item.setSendAction(new ChatItemDepartmentSendEvent(key));
			item.setCloseAction(new ChatItemCloseEvent(key));
			item.setOnWriteKeyReleased(e -> {// 回车发送
				if (!e.isShiftDown() && e.getCode() == KeyCode.ENTER) {
					sendDepartmentMessage(key);
					e.consume();
				}
			});

			chatPanelMap.put(key, item);
			setDepartmentUserListPane(item, department.getId());

			EventAction<FaceInfo> faceAction = new EventAction<FaceInfo>() {

				NodeChatPane item;

				@Override
				public void execute(FaceInfo value) {
					if (null != value) {
						sendDepartmentFace(departmentId, item, value);
					}
				}

				EventAction<FaceInfo> set(NodeChatPane item) {
					this.item = item;
					return this;
				}
			}.set(item);

			// 表情按钮
			Image normalImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_face.png");
			Image hoverImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_face_hover.png");
			Image pressedImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_face_hover.png");
			final IconPane ib = new IconPane(normalImage, hoverImage, pressedImage);
			ib.setOnMouseClicked(new EventHandler<MouseEvent>() {

				@Override
				public void handle(MouseEvent event) {
					faceSelectAction = (faceAction);
					facePopup.show(ib);
				}
			});
			item.addMiddleTool(ib);
			// 发送图片按钮
			normalImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_sendpic.png");
			hoverImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_sendpic_hover.png");
			pressedImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_sendpic_hover.png");

			IconPane iconButton = new IconPane(normalImage, hoverImage, pressedImage);
			EventHandler<MouseEvent> e = new EventHandler<MouseEvent>() {
				NodeChatPane item;

				@Override
				public void handle(MouseEvent event) {
					String fullPath = getPicture();
					sendDepartmentImage(departmentId, item, fullPath);
				}

				EventHandler<MouseEvent> set(NodeChatPane item) {
					this.item = item;
					return this;
				}
			}.set(item);
			iconButton.setOnMouseClicked(e);
			item.addMiddleTool(iconButton);

			EventAction<Image> screenShotAction = new EventAction<Image>() {
				NodeChatPane item;

				@Override
				public void execute(Image image) {
					if (null != image) {
						String fullPath =saveImage(item, image);
						sendDepartmentImage(departmentId, item, fullPath);
					}
				}

				EventAction<Image> set(NodeChatPane item) {
					this.item = item;
					return this;
				}
			}.set(item);
			// 截屏按钮
			normalImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_cut.png");
			hoverImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_cut.png");
			pressedImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_cut.png");

			iconButton = new IconPane(normalImage, hoverImage, pressedImage);
			iconButton.setOnMouseClicked(new EventHandler<MouseEvent>() {

				@Override
				public void handle(MouseEvent event) {
					frame.setOnImageAction(screenShotAction);
					frame.setVisible(true);
				}
			});
			item.addMiddleTool(iconButton);

		}
		item.setName(department.getName());
		// item.setText(department.getPublicNotice());
		return item;
	}

	private void sendDepartmentMessage(String key) {
		PersonalBox pb = appContext.getBox(PersonalBox.class);
		UserData user = pb.getUserData();
		NodeChatPane chatPanel = chatPanelMap.get(key);
		if (null != chatPanel) {
			String text = chatPanel.getWriteText();

			boolean underline = chatPanel.isUnderline();
			boolean bold = chatPanel.isBold();
			String color = chatPanel.getWebColor();
			boolean italic = chatPanel.isItalic();
			String fontName = chatPanel.getFontName();
			int fontSize = chatPanel.getFontSize();
			String departmentId = chatPanel.getAttribute("departmentId");

			if (StringUtils.isNotBlank(text)) {

				chatPanel.initializeWriteHtml();

				Content content = getContent(Item.type_text, text);
				com.onlyxiahui.im.message.data.chat.Font font = new com.onlyxiahui.im.message.data.chat.Font();
				font.setBold(bold);
				font.setColor(color);
				font.setItalic(italic);
				font.setName(fontName);
				font.setSize(fontSize);
				font.setUnderline(underline);
				content.setFont(font);

				DepartmentChatSender ch = appContext.getSender(DepartmentChatSender.class);
				ch.sendDepartmentChatMessage(departmentId, user.getId(), content);
			}
		}
	}

	private void setDepartmentUserListPane(NodeChatPane item, String departmentId) {
		ListRootPanel departmentUserList = departmentUserListMap.get(departmentId);
		if (null == departmentUserList) {
			updateDepartmentUserList(departmentId);
		} else {
			if (null != item) {
				departmentUserList.setPrefWidth(140);
				item.setRightPane(departmentUserList);
			}
		}
	}

	public void updateDepartmentUserList(final String departmentId) {
		DepartmentManage dm = appContext.getManager(DepartmentManage.class);
		List<String> userIdList = dm.getDepartmentMemberIdListIncludeNode(departmentId);
		if (null != userIdList) {
			UserDataBox ub = appContext.getBox(UserDataBox.class);
			List<UserData> userDataList = new ArrayList<UserData>();
			for (String userId : userIdList) {
				UserData ud = ub.getUserData(userId);
				if (null != ud) {
					userDataList.add(ud);
				}
			}
			setDepartmentUserList(departmentId, userDataList);
		}
	}

	private void setDepartmentUserList(String departmentId, List<UserData> userDataList) {
		Platform.runLater(new Runnable() {
			@Override
			public void run() {

				ListRootPanel departmentUserList = departmentUserListMap.get(departmentId);
				if (departmentUserList == null) {
					departmentUserList = new ListRootPanel();
				}
				departmentUserList.clearNode();
				for (UserData userData : userDataList) {
					SimpleHead item = new SimpleHead();

					item.setOnMouseClicked((MouseEvent me) -> {
						if (me.getClickCount() == 2) {
							ChatManage chatManage = appContext.getManager(ChatManage.class);
							chatManage.showCahtFrame(userData);
						}
						me.consume();
					});
					String text = userData.getRemarkName();
					if (null == text || "".equals(text)) {
						text = userData.getName();
					}
					if (null == text || "".equals(text)) {
						text = userData.getNickname();
					}
					if (null == text || "".equals(text)) {
						text = userData.getAccount();
					}
					item.setText(text);
					HeadImageManager him = appContext.getManager(HeadImageManager.class);
					Image image = him.getUserHeadImage(userData.getId(), userData.getHead(), 40);

					item.setHeadSize(20);
					item.setHeadRadius(20);
					item.setImage(image);

					item.addAttribute(UserData.class, userData);
					departmentUserList.addNode(item);
				}

				String key = getDepartmentKey(departmentId);
				NodeChatPane chatPanel = chatPanelMap.get(key);
				if (null != chatPanel) {
					departmentUserList.setPrefWidth(140);
					chatPanel.setRightPane(departmentUserList);
				}
			}
		});
	}

	private class ChatItemDepartmentSendEvent implements EventHandler<ActionEvent> {

		String key;

		public ChatItemDepartmentSendEvent(String key) {
			this.key = key;
		}

		@Override
		public void handle(ActionEvent event) {
			sendDepartmentMessage(key);
		}
	}

	private String getDepartmentKey(String departmentId) {
		StringBuilder sb = new StringBuilder();
		sb.append("department_");
		sb.append(departmentId);
		return sb.toString();
	}

	protected NodeChatPane getUserChatPanel(UserData userData) {
		String userId = userData.getId();
		String key = this.getUserKey(userData.getId());
		NodeChatPane item = chatPanelMap.get(key);
		if (null == item) {
			item = new NodeChatPane();
			item.addAttribute("key", key);
			item.addAttribute("userId", userData.getId());
			item.setSendAction(new ChatItemUserSendEvent(key));
			item.setCloseAction(new ChatItemCloseEvent(key));
			item.setOnWriteKeyReleased(e -> {// 回车发送
				if (!e.isShiftDown() && e.getCode() == KeyCode.ENTER) {
					sendUserMessage(key);
					e.consume();
				}
			});

			EventAction<FaceInfo> faceAction = new EventAction<FaceInfo>() {

				NodeChatPane item;

				@Override
				public void execute(FaceInfo value) {
					if (null != value) {
						sendUserFace(userId, item, value);
					}
				}

				EventAction<FaceInfo> set(NodeChatPane item) {
					this.item = item;
					return this;
				}
			}.set(item);

			// 表情按钮
			Image normalImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_face.png");
			Image hoverImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_face_hover.png");
			Image pressedImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_face_hover.png");
			IconPane ib = new IconPane(normalImage, hoverImage, pressedImage);
			ib.setOnMouseClicked(new EventHandler<MouseEvent>() {

				@Override
				public void handle(MouseEvent event) {
					faceSelectAction = (faceAction);
					facePopup.show(ib);
				}
			});
			item.addMiddleTool(ib);
			// 发送图片按钮
			normalImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_sendpic.png");
			hoverImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_sendpic_hover.png");
			pressedImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_sendpic_hover.png");

			IconPane iconButton = new IconPane(normalImage, hoverImage, pressedImage);
			EventHandler<MouseEvent> e = new EventHandler<MouseEvent>() {
				NodeChatPane item;

				@Override
				public void handle(MouseEvent event) {
					String fullPath = getPicture();
					sendUserImage(userId, item, fullPath);
				}

				EventHandler<MouseEvent> set(NodeChatPane item) {
					this.item = item;
					return this;
				}
			}.set(item);
			iconButton.setOnMouseClicked(e);
			item.addMiddleTool(iconButton);

			EventAction<Image> screenShotAction = new EventAction<Image>() {
				NodeChatPane item;

				@Override
				public void execute(Image image) {
					if (null != image) {
						String fullPath = saveImage(item, image);
						sendUserImage(userId, item, fullPath);
					}
				}

				EventAction<Image> set(NodeChatPane item) {
					this.item = item;
					return this;
				}
			}.set(item);
			// 截屏按钮
			normalImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_cut.png");
			hoverImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_cut.png");
			pressedImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_cut.png");

			iconButton = new IconPane(normalImage, hoverImage, pressedImage);
			iconButton.setOnMouseClicked(new EventHandler<MouseEvent>() {

				@Override
				public void handle(MouseEvent event) {
					frame.setOnImageAction(screenShotAction);
					frame.setVisible(true);
				}
			});
			item.addMiddleTool(iconButton);

			normalImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_twitter.png");

			iconButton = new IconPane(normalImage);
			item.addMiddleTool(iconButton);

			iconButton.setOnMouseClicked(new EventHandler<MouseEvent>() {

				@Override
				public void handle(MouseEvent event) {
					sendShake(userData.getId());
				}
			});

			// normalImage =
			// ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/GVideoTurnOnVideo.png");
			//
			// iconButton = new IconButton(normalImage);
			// item.addMiddleTool(iconButton);
			//
			// iconButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
			//
			// @Override
			// public void handle(MouseEvent event) {
			// sendVideo(userData);
			// }
			// });

			normalImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_register.png");
			hoverImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_register_hover.png");
			pressedImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_register.png");

			iconButton = new IconPane("消息记录", normalImage, hoverImage, pressedImage);
			iconButton.setOnMouseClicked(new EventHandler<MouseEvent>() {

				@Override
				public void handle(MouseEvent event) {
					showChatHistoryView(userData.getId());
					PromptManager pm = appContext.getManager(PromptManager.class);
					pm.remove("offline," + userData.getId());// 系统托盘停止跳动
				}
			});

			item.addMiddleRightTool(iconButton);

			chatPanelMap.put(key, item);
			StackPane rightPane = new StackPane();
			// rightPane.setPrefHeight(350);
			// rightPane.setMaxHeight(350);
			ImageView imageView = new ImageView();
			rightPane.getChildren().add(imageView);

			if (!"2".equals(userData.getGender())) {
				Image image = ImageBox.getImagePath("Resources/Images/Default/Show/default_av_girl_v3.png", 140, 380);
				imageView.setImage(image);
			} else {
				Image image = ImageBox.getImagePath("Resources/Images/Default/Show/default_av_boy_v3.png", 140, 380);
				imageView.setImage(image);
			}
			//item.setRightPane(rightPane);

			Image i = ImageBox.getImageClassPath("/resources/chat/images/user/file/aio_toobar_send_hover.png");

			IconButton isb = new IconButton();
			isb.setNormalImage(i);
			item.addTopTool(isb);

			isb.setOnAction(a -> {
				UserDataBox ub = appContext.getBox(UserDataBox.class);
				boolean online = ub.isOnline(userId);
				if (online) {
					File file = fileChooser.showOpenDialog(chatListFrame);
					if (null != file) {
						SettingManager sm = appContext.getManager(SettingManager.class);
						if (file.length() > sm.getChatSetting().getFileLimitSize()) {
							chatListFrame.showPrompt(sm.getChatSetting().getFileLimitInfo());
							return;
						}
						ChatController cc = appContext.getController(ChatController.class);
						cc.sendFile(userData.getId(), file);
					}
				} else {
					chatListFrame.showPrompt("对方不在线！");
				}
			});

			item.setFileEventAction(file -> {
				if (null != file) {
					UserDataBox ub = appContext.getBox(UserDataBox.class);
					boolean online = ub.isOnline(userId);
					if (online) {
						SettingManager sm = appContext.getManager(SettingManager.class);
						if (file.length() > sm.getChatSetting().getFileLimitSize()) {
							chatListFrame.showPrompt(sm.getChatSetting().getFileLimitInfo());
							return;
						}
						ChatController cc = appContext.getController(ChatController.class);
						cc.sendFile(userData.getId(), file);
					} else {
						chatListFrame.showPrompt("对方不在线！");
					}
				}
			});

			i = ImageBox.getImageClassPath("/resources/chat/images/user/top/Remote_MenuTextue2.png");

			isb = new IconButton();
			isb.setNormalImage(i);
			item.addTopTool(isb);

			isb.setOnAction(a -> {
				UserDataBox ub = appContext.getBox(UserDataBox.class);
				boolean online = ub.isOnline(userId);
				if (online) {
					RemoteController rc = appContext.getController(RemoteController.class);
					rc.requestRemoteControl(userId);
				} else {
					chatListFrame.showPrompt("对方不在线！");
				}
			});
		}

		String text = AppCommonUtil.getDefaultShowName(userData);
		item.setName(text);
		item.setText(userData.getSignature());
		return item;
	}

	private void sendDepartmentImage(String departmentId, NodeChatPane cp, String imageUrl) {
		if(StringUtils.isBlank(imageUrl)) {
			return;
		}

		if (!imageUrl.startsWith("file")) {
			if (!imageUrl.startsWith("/")) {
				imageUrl="/"+imageUrl;
			} 
			imageUrl="file:"+imageUrl;
		} 
		
		PersonalBox pb = appContext.getBox(PersonalBox.class);
		String ownerId = pb.getOwnerUserId();
		Content content = getContent(Item.type_image, imageUrl);
		com.onlyxiahui.im.message.data.chat.Font font = new com.onlyxiahui.im.message.data.chat.Font();
		content.setFont(font);
		List<Item> items = ContentUtil.getImageItemList(content);
		ImageManager im = this.appContext.getManager(ImageManager.class);
		BackAction<List<FileHandleInfo>> backAction = new BackAction<List<FileHandleInfo>>() {

			@Override
			public void back(BackInfo backInfo, List<FileHandleInfo> t) {
				DepartmentChatSender ch = appContext.getSender(DepartmentChatSender.class);
				ch.sendDepartmentChatMessage(departmentId, ownerId, content);
			}
		};
		im.uploadImage(items, backAction);
	}

	private void sendDepartmentFace(String departmentId, NodeChatPane cp, FaceInfo fd) {

		PersonalBox pb = appContext.getBox(PersonalBox.class);
		String ownerId = pb.getOwnerUserId();
		String categoryId = fd.getCategoryId();
		String key = fd.getKey();
		String value = categoryId + "," + key;

		Content content = getContent(Item.type_face, value);
		com.onlyxiahui.im.message.data.chat.Font font = new com.onlyxiahui.im.message.data.chat.Font();
		content.setFont(font);
		DepartmentChatSender ch = appContext.getSender(DepartmentChatSender.class);
		ch.sendDepartmentChatMessage(departmentId, ownerId, content);
	}

}
